const express = require('express')
const { queryDBPromise } = require('../util/db')
const userRouter = express.Router() // 路由对象

// 路由接口
/**
 * 获取所有用户列表
 */
userRouter.get('/users', (req, res) => {
	const sql = `SELECT id,username,password,age FROM users`
	queryDBPromise(sql)
		.then(data => {
			res.send({
				code: 1,
				list: data,
			})
		})
		.catch(err => {
			res.send({
				code: -1,
				message: '查看用户列表失败!',
			})
		})
})

/**
 * 添加用户
 *   method: POST
 *   url:  /user
 *   参数:  username   password  age
 *
 */
userRouter.post('/register', (req, res) => {
	// 接收参数
	const username = req.body.username
	const password = req.body.password
	const age = req.body.age

	// 判断用户是否已经注册
	const sql1 = `SELECT count(*) AS num FROM users WHERE username = '${username}'`
	queryDBPromise(sql1).then(data => {
		if (data[0].num > 0) {
			res.send({
				code: -1,
				message: '该用户名已经注册！',
			})
		} else {
			// 添加到用户表
			const sql = `INSERT INTO users (username,password,age)VALUES('${username}','${password}',${age})`
			queryDBPromise(sql)
				.then(data => {
					res.send({
						code: 1,
						message: '注册用户成功!',
					})
				})
				.catch(err => {
					res.send({
						code: -1,
						messdage: '注册用户失败',
					})
				})
		}
	})
})

/**
 * 用户登录
 *  method:post
 *  url: /login
 *  参数: username password
 */
userRouter.post('/login', (req, res) => {
	const username = req.body.username //用户名
	const password = req.body.password //密码

	// 登录本质: 根据用户名和密码，查询数据库用户表，有无该记录
	const sql = `SELECT count(*) AS num FROM users WHERE username = '${username}' AND password = '${password}'`
	queryDBPromise(sql).then(data => {
		console.log('data >> :', data)

		if (data[0].num > 0) {
			res.send({
				code: 1,
				message: '登录成功',
			})
		} else {
			res.send({
				code: -1,
				message: '用户名或密码出错!',
			})
		}
	})
})

// 暴露路由对象
module.exports = { userRouter }
